import {
  _decorator,
  Component,
  Node,
  instantiate,
  Label,
  SpriteFrame,
  Sprite,
  ToggleContainer,
  Toggle,
} from "cc";
import { BasePanel } from "../../core/component/BasePanel";
import ClickDelegate from "../../core/component/ClickDelegate";
import { Engine } from "../../core/Engine";
import { TabMenu } from "../component/TabMenu";
import { dataManager } from "../data/DataManager";
import { EVENT_NAME } from "../GameConstant";
const { ccclass, property } = _decorator;

/**
 * Predefined variables
 * Name = BuildListPanel
 * DateTime = Sun Dec 19 2021 23:18:29 GMT+0800 (中国标准时间)
 * Author = han2007happy
 * FileBasename = BuildListPanel.ts
 * FileBasenameNoExtension = BuildListPanel
 * URL = db://assets/scripts/game/map/BuildListPanel.ts
 * ManualUrl = https://docs.cocos.com/creator/3.3/manual/en/
 *
 */

@ccclass("BuildListPanel")
export class BuildListPanel extends BasePanel {
  @property({ type: Node, displayName: "建造列表" })
  buildList!: Node;

  @property({ type: TabMenu, displayName: "建筑分类" })
  buildCategoryMenu!: TabMenu;

  private cityId!: string;

  private currentTabId = 0;

  show(cityId: string, requiredBuildTyps: number[]) {
    this.cityId = cityId;
    this.buildCategoryMenu.initMenus(
      null,
      0,
      this.filterBuildingCategory,
      this
    );
    this.filterBuildingCategory(0);
  }

  // 建筑筛选
  private filterBuildingCategory(tabIdx: number) {
    this.currentTabId = tabIdx;
    this.renewView();
  }

  //
  renewView() {
    const buildListData: { [id: string]: Building } =
      dataManager.dataMap.getBuildList(this.currentTabId + 1);
    const buildTempNode = this.buildList.children[0];
    let buildIdx = 0;
    for (const key in buildListData) {
      let buildItemNode = this.buildList.children[buildIdx];
      if (!buildItemNode) {
        buildItemNode = instantiate(buildTempNode);
        buildItemNode.parent = this.buildList;
      }

      const buidInfo: Building = buildListData[key];
      buildItemNode
        .getChildByName("name")!
        .getComponent(Label)!.string = `${buidInfo.name}`;
      buildItemNode
        .getChildByName("des")!
        .getComponent(Label)!.string = `${buidInfo.des}`;
      const buildIcon = buildItemNode
        .getChildByName("icon")!
        .getComponent(Sprite)!;
      Engine.resManager
        .loadPath<SpriteFrame>("textures/map/" + buidInfo.res + "/spriteFrame")
        .then((sprFame: SpriteFrame) => {
          buildIcon.spriteFrame = sprFame;
        });

      buildItemNode
        .getComponent(ClickDelegate)!
        .init(this, this.selectedBuild, key);
      buildIdx++;
    }
  }

  // 选择建筑
  private selectedBuild(buildId: string) {
    dataManager.dataPlayer.addBuilding(this.cityId, buildId);

    this.close();
  }
}
